<?php
define("MY_SESS_TIME", 3600);
class session
{
	private static $config;
	
	private static $dbh;
	
	private static $slaveDBH;
	
	static function init()
	{
		global $config, $dbh, $slaveDBH;
		self::$config = $config;
		self::$dbh = $dbh;
		self::$slaveDBH = $slaveDBH;
		
		session_set_save_handler(
				array("session","open"),
				array("session","close"),
				array("session","read"),
				array("session","write"),
				array("session","destroy"),
				array("session","gc")
		);
	}
	
	static function open($save_path,$session_name)
	{
		/*global $db,$REMOTE_ADDR;
		 $rs = $db->Execute("select * from Sessions where SessionID='".session_id()."'");
		$arry=$rs->FetchRow();
		if( $rs && $arry)
		{
		$db->Execute("update Sessions set SessionLast=NOW() where SessionID='".session_id()."'");
		}
		else
		{
		$query = "insert into Sessions set SessionID='".session_id()."',SessionName='$REMOTE_ADDR',SessionLast='NOW()'";
		//echo $query;
		$db->Execute($query);
		}*/
		return true;
	}
	static function close()
	{
		return(true);
	}
	
	static function read($id)
	{
		$timenow = strftime("%Y-%m-%d %H:%M:%S", time());
		$query_sql = "select SessionData from Sessions where SessionID='$id' and SessionLast > '$timenow'";
		$rs = self::$dbh->query($query_sql)->fetch();
		if($rs)
		{
			return $rs->SessionData;
		}
		else
		{
			return false;
		}
	}
	
	static function write($id,$sess_data)
	{
		$rs = self::$dbh->query("select SessionID from Sessions where SessionID='$id'")->fetch();
		$unix_time = time()+MY_SESS_TIME;
		//echo MY_SESS_TIME;
		$dateleft = strftime("%Y-%m-%d %H:%M:%S", $unix_time);
		if(!$rs)
		{
			$sql = "insert into Sessions set SessionData='$sess_data', SessionName='".$_SERVER["REMOTE_ADDR"]."', SessionLast='$dateleft', SessionID='".session_id()."'";
		}
		else
		{
			$sql = "update Sessions set SessionData='$sess_data', SessionName='".$_SERVER["REMOTE_ADDR"]."', SessionLast='$dateleft' where SessionID='$id'";
		}
		self::$dbh->exec($sql);
	}
	
	static function destroy($id)
	{
		$sql = "DELETE FROM Sessions WHERE `SessionID` = '$id'";
		$rs = self::$dbh->Execute($sql);
		return $rs;
		// $sess_file = "$sess_save_path/sess_$id";
		//return(@unlink($sess_file));
	}
	
	/*********************************************
	 * WARNING - You will need to implement some *
	* sort of garbage collection routine here. *
	*********************************************/
	static function gc($maxlifetime)
	{
		$timenow = strftime("%Y-%m-%d %H:%M:%S", time());
		$sql = "DELETE FROM `$table_sessions` WHERE `SessionLast` < '$timenow'";
		return self::$dbh->Execute($sql);
		//echo "now gc!<br>";
		return true;
	}
	// proceed to use sessions normally
}